//
//
//  NSobject+YDTheme.m
//
//  Created by kf on 2017/8/11.
//  Copyright © 2017年 IngDan. All rights reserved.
//
#import "UIView+YDTheme.h"
#import "YDTheme.h"
#import <objc/runtime.h>

static void *YDObjectStyleChangedKey = "YDObjectStyleChangedKey";

@interface UIView ()
@property(nonatomic, copy) OnStyleChanged onStyleChanged;
@property(nonatomic, assign) BOOL hasNotification;
@end

@implementation UIView (YDTheme)

- (void)ea_dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:THEME.Notification_ThemeChanged object:nil];
    [self ea_dealloc];
}

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Method deallocMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
        Method ea_deallocMethod = class_getInstanceMethod([self class], @selector(ea_dealloc));
        method_exchangeImplementations(deallocMethod, ea_deallocMethod);
    });
    
}


- (void) setStyle:(OnStyleChanged)onStyleChanged
{
    if (onStyleChanged)
    {
        if(!self.onStyleChanged)
        {
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(changeStyle)
                                                         name:THEME.Notification_ThemeChanged
                                                       object:nil];
        }
        
        self.onStyleChanged = onStyleChanged;
        [self changeStyle];
    }
}

- (void) changeStyle
{
    if (self.onStyleChanged)
    {
        dispatch_async_main(^{
            self.onStyleChanged(self);
        });
    }
}

#pragma mark - lazy loading
- (void) setOnStyleChanged:(OnStyleChanged)onStyleChanged
{
    objc_setAssociatedObject(self, YDObjectStyleChangedKey, onStyleChanged, OBJC_ASSOCIATION_COPY);
}

- (OnStyleChanged)onStyleChanged {

    return objc_getAssociatedObject(self, YDObjectStyleChangedKey);
}

@end
